#! /usr/bin/env python
#coding:utf8

import sys
import MySQLdb
import json

reload(sys)
sys.setdefaultencoding('utf-8')

# tables = ('test_table',)
# vo = ('test_table',)
# ('test_table') is interpreted as using algebraic grouping and simply as max_price and not a tuple.
#  Adding a comma, i.e. ('test_table',) forces it to make a tuple.


head = '''using UnityEngine;
using System;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
'''
class_part1 = '''public class %s
{
'''
field =\
'''    public %s %s;
'''
ctor_par1 =\
'''
    public %s(string[] arr)
    {
'''
ctor_field =\
'''         this.%s=%s(arr[%s]);
'''
ctor_par2 =\
'''    }
'''
class_part2 =\
'''
    public override string ToString()
    {
        StringBuilder builder = new StringBuilder();

        FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (var item in fields)
        {
            builder.Append(item.Name + " : " + item.GetValue(this));
        }

        return builder.ToString();
    }
}
'''

def ConvetType(typeid):
    if typeid == 3:
        return 'int'
    elif typeid == 4:
        return 'float'
    else:
        return 'string'

def ConvertCtorType(typeid):
    if typeid == 3:
        return 'int.Parse'
    elif typeid == 4:
        return 'float.Parse'
    else:
        return ''

# description (('id', 3, 1, 11, 11, 0, 0), ('name', 253, 6, 765, 765, 0, 0), ('price', 4, 1, 12, 12, 31, 0))
def CreateCS(index, description):
    vo = curconifg['vos']
    with open('%s.cs'% vo[index],"w+") as my_cs:
        my_cs.write(head)
        my_cs.write(class_part1 % vo[index])
        for colIndex in range(len(description)):
            curCol = description[colIndex]
            my_cs.write(field % (ConvetType(curCol[1]),curCol[0]))
        my_cs.write(ctor_par1 % vo[index])
        for colIndex in range(len(description)):
             curCol = description[colIndex]
             my_cs.write(ctor_field % (curCol[0],ConvertCtorType(curCol[1]),colIndex))
        my_cs.write(ctor_par2)
        my_cs.write(class_part2)

def CreateConfig():
    con = MySQLdb.connect(curconifg['db']['host'],curconifg['db']['user'],curconifg['db']['passwd'],curconifg['db']['db'],charset='utf8');
    # notice ,charset='utf8'
    with con:
        cur = con.cursor()
        tables = curconifg['tables']
        for index in  range(len(tables)):
            table = tables[index]
            # cur.execute("select * from %s where id = %s",('test_table',1))
            # DB API requires you to pass in any parameters as a sequence
            # but sql query is select * from \\'test_table\\' where id = 1
            # like below error
            # http://blog.xupeng.me/2013/09/25/mysqldb-args-processing
            # so you can do it below,but not safe
            query = 'select * from %s '%(table);
            cur.execute(query)
            with open('%s.txt'%(table),'w+') as my_txt:
            # create file if not exits
                description = cur.description
                CreateCS(index,description)
                # description (('id', 3, 1, 11, 11, 0, 0), ('name', 253, 6, 765, 765, 0, 0), ('price', 4, 1, 12, 12, 31, 0))
                # create txt
                line = curconifg['exp_sep'].join(str(curCol[0]) for curCol in description)
                # id	name	price
                my_txt.write(line+'\n')
                for i in range(cur.rowcount):
                    row = cur.fetchone()
                    line = curconifg['exp_sep'].join(str(col) for col in row)
                    # 1	张三	3.0
                    if(i < (cur.rowcount - 1)):
                         my_txt.write(line+'\n')
                    else:
                         my_txt.write(line)

with open("config.json","r") as jsonFile:
    curconifg = json.load(jsonFile)
    CreateConfig()









